package com.shopping.controller;


import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.shopping.po.User;
import com.shopping.po.UserInfor;
import com.shopping.service.UserService;


@Controller
public class UserController {
	@Autowired
	private UserService userService;
	
	
	@RequestMapping("/toregister")
	public String toregister() {
		return "register";
	}
	//访问的主页面，进行登录操作等
	@RequestMapping("/index")
	public String toindex() {
		return "index";
	}
	
	@RequestMapping("/tologin")
	public String tologin() {
		return "login";
	}
	
	//登录验证,验证成功后去执行selectGoods即商品的展示
		@RequestMapping(value="/login",method=RequestMethod.POST)
		public String check2(HttpServletRequest request,HttpSession session) {
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			User user1 = userService.findUserByName(username);
			if(user1 != null) {
				if(user1.getPassword().equals(password)) {
					session.setAttribute("user", user1);
					return "redirect:/selectGoods";
				}else {
					request.setAttribute("password", "密码错误");
					return "login";
				}
			}else {
				request.setAttribute("username", "用户不存在");
				return "login";
			}
			
		}
	
	@RequestMapping("/register")
	public String check(HttpServletRequest request, User user) {
 		String username = request.getParameter("username");
 		String password = request.getParameter("password");
 		String password2 = request.getParameter("password2");
 		User user1 = userService.findUserByName(username);
 		if (username == null || username.trim().equals("")) {
 			request.setAttribute("username", "请输入姓名.");
 			return "register";
 		}
 		if (password == null || password.trim().equals("")) {
 			request.setAttribute("password", "请输入密码.");
 			return "register";
 		} else if (password.length() > 12 || password.length() < 6) {
 			request.setAttribute("password", "请输入6-12个字符.");
 			return "register";
 		}
 		if (password != null && !password.equals(password2)) {
 			request.setAttribute("password2", "两次输入的密码不匹配.");
 			return "register";
 		}
 		if(user1 == null) {
 			userService.addUser(user);
 			request.setAttribute("username","注册成功,在这里登陆即可");
 			return "login";
 		}else {
			request.setAttribute("username","已存在此用户,在这里登陆即可");
			return "login";
		}
 	}
	
	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:/login";	
	}
	
}
